package online.sixfish.doubao.controller.admin;

import online.sixfish.common.api.ApiResult;
import online.sixfish.doubao.event.CoursewareDownloadEvent;
import online.sixfish.doubao.model.entity.Courseware;
import online.sixfish.doubao.model.vo.CoursewareUpdateVO;
import online.sixfish.doubao.service.CoursewareService;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
@CrossOrigin
@RequestMapping("/admin/courseware")
public class AdminCoursewarecontroller {

    @Resource
    CoursewareService coursewareService;

    @GetMapping("/download/{id}")
    @PreAuthorize("hasRole('admin')")
    public ResponseEntity download(@PathVariable Integer id) throws IOException {
        byte[] bytes = coursewareService.download(id);
        Courseware courseware = coursewareService.findById(id);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", courseware.getName());
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @PostMapping("/update")
    @PreAuthorize("hasRole('admin')")
    public ApiResult update(@RequestBody CoursewareUpdateVO coursewareUpdateVO) {
        Courseware courseware = new Courseware();
        BeanUtils.copyProperties(coursewareUpdateVO, courseware);
        coursewareService.update(courseware);
        return ApiResult.success();

    }

    @PostMapping("/delete/{id}")
    @PreAuthorize("hasRole('admin')")
    public ApiResult delete(@PathVariable Integer id) {
        coursewareService.delete(id);
        return ApiResult.success();
    }
}
